package com.example.demo2.controller;

import com.example.demo2.entity.Comparison;
import com.example.demo2.entity.Program;
import com.example.demo2.mapper.ComparisonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/comparison")
@CrossOrigin
public class ComparisonController {

    @Autowired
    private ComparisonMapper comparisonMapper;

    private static final String SERVER_UPLOAD_DIR = "D:\\file\\pdf";

    // 导出对比测试数据
    @GetMapping("/export")
    public ResponseEntity<Resource> exportComparisons() throws IOException {
        List<Comparison> comparisons = comparisonMapper.selectAllComparisons();
        String fileName = "comparisons-" + System.currentTimeMillis() + ".xlsx";
        Path excelPath = Paths.get(SERVER_UPLOAD_DIR).resolve(fileName).normalize();
        // Assuming ComparisonExcelService is implemented elsewhere
        // comparisonExcelService.exportComparisonsToExcel(comparisons, excelPath.toString());

        Resource resource = new UrlResource(excelPath.toUri());
        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    private Map<String, String> currentPlan = null;

    @GetMapping("/current-plan")
    public ResponseEntity<Map<String, Object>> getCurrentPlan(@RequestParam("pjId") int pjId ) {
        Map<String, Object> response = new HashMap<>();
        System.out.println("这是pjID"+pjId);
        Program lll = comparisonMapper.findComparisonBypjID(Integer.valueOf(pjId),"比对方案");
        Map<String, String> responseData = new HashMap<>();
        String originalFilename = lll.getPgUrl().substring(10);
        responseData.put("fileName", originalFilename);
        responseData.put("fileUrl", lll.getPgUrl());
        response.put("code", 200);
        response.put("data",responseData);
        return ResponseEntity.ok(response);
    }
    class MyClass{
        int projectId;
        MultipartFile file;

        public int getProjectId() {
            return projectId;
        }

        public void setProjectId(int projectId) {
            this.projectId = projectId;
        }

        public MultipartFile getFile() {
            return file;
        }

        public void setFile(MultipartFile file) {
            this.file = file;
        }
    }
    @PostMapping("/uploadPDF")
    public ResponseEntity<String> uploadPDF(@RequestParam("file")  MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();
            String filename = UUID.randomUUID().toString() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

            Path path = Paths.get(SERVER_UPLOAD_DIR, filename);
            Files.createDirectories(path.getParent());

            Files.write(path, file.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok("上传成功，");
    }

    @PostMapping("/uploadPDF1")
    public ResponseEntity<String> uploadPDF1(@RequestParam("originalFilename")  String originalFilename ,@RequestParam("projectId") String projectId) throws IOException {
//       int projectId = formData.getProjectId();
//       MultipartFile file =formData.getFile();
        int pjId = Integer.parseInt(projectId);


        System.out.println("555555555555555555555555555555"+"调用上传pdf");
        // String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
//
//            Path path = Paths.get(SERVER_UPLOAD_DIR, filename);
//            Files.createDirectories(path.getParent());
//            Files.write(path, file.getBytes());

        // 返回HTTP可访问的URL
        String fileUrl = "/file/pdf/" + filename;

        // 更新数据库记录
        int result = comparisonMapper.updateComparisonFilePath(pjId, fileUrl);
        if (result == 0) {
            return ResponseEntity.status(500).body("文件上传成功，但数据库更新失败");
        }

        return ResponseEntity.ok("上传成功，文件URL：" + fileUrl);
    }

    @DeleteMapping("/delete-plan")
    public ResponseEntity<Map<String, Object>> deletePlan() {
        Map<String, Object> response = new HashMap<>();

        if (currentPlan != null) {
            try {
                String fileUrl = currentPlan.get("fileUrl");
                String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                Path filePath = Paths.get(SERVER_UPLOAD_DIR, filename);
                Files.deleteIfExists(filePath);

                currentPlan = null;

                response.put("code", 200);
                response.put("data", null);
                response.put("message", "删除成功");
                return ResponseEntity.ok(response);
            } catch (IOException e) {
                e.printStackTrace();
                response.put("code", 500);
                response.put("data", null);
                response.put("message", "删除失败：" + e.getMessage());
                return ResponseEntity.status(500).body(response);
            }
        }

        response.put("code", 200);
        response.put("data", null);
        response.put("message", "无方案可删除");
        return ResponseEntity.ok(response);
    }
    // 修改PDF文件
    @PutMapping("/updatePDF/{cpId}")
    public ResponseEntity<String> updatePDF(@PathVariable Integer cpId, @RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Empty file");
        }

        Comparison comparison = comparisonMapper.selectComparisonById(cpId);
        if (comparison == null) {
            return ResponseEntity.badRequest().body("Comparison not found");
        }

        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        Path path = Paths.get(SERVER_UPLOAD_DIR).resolve(filename).normalize();
        Files.write(path, file.getBytes());
        comparison.setFilePath(path.toString());

        comparisonMapper.updateComparison(comparison);
        String url访问地址 = "http://localhost:8080/comparison/download/" + filename; // 假设应用运行在localhost:8080
        return ResponseEntity.ok(url访问地址);
    }

    // 更新对比测试
    @PutMapping("/updateComparison/{cpId}")
    public String updateComparison(@PathVariable Integer cpId, @RequestBody Comparison comparison) {
        try {
            System.out.println("Updating comparison with ID: " + cpId);
            System.out.println("Received data: " + comparison.toString());
            System.out.println("状态值edqsafafa:"+comparison.getCpStatus());

            // 获取现有记录
            Comparison existingComparison = comparisonMapper.selectComparisonById(cpId);
            if (existingComparison == null) {
                return "Comparison not found";
            }

            // 更新字段
            // existingComparison.setuID(comparison.getuID());
            //  existingComparison.setPjId(comparison.getPjId());
            // existingComparison.setStartDate(comparison.getStartDate());
            //  existingComparison.setEndDate(comparison.getEndDate());
            existingComparison.setCpStatus(comparison.getCpStatus());
            //  existingComparison.setFilePath(comparison.getFilePath());

            // 执行更新
            int result = comparisonMapper.updateComparison(existingComparison);

            if (result > 0) {
                return "Comparison updated successfully";
            } else {
                return "Update failed";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Update failed: " + e.getMessage();
        }
    }
    // 获取所有对比测试
    @GetMapping("/list")
    public List<Comparison> listComparisons() {
        // System.out.println("shuju:"+comparisonMapper.selectAllComparisons().get(0).getPjId());
        return comparisonMapper.selectAllComparisons();
    }

    // 删除对比测试
    @DeleteMapping("/deleteComparison/{cpId}")
    public String deleteComparison(@PathVariable Integer cpId) {
        comparisonMapper.deleteComparison(cpId);
        return "Comparison deleted successfully";
    }
}
